package com.yyk.yykywd.ui.customer;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yykywd.R;
import com.yyk.yykywd.base.BaseActivity;
import com.yyk.yykywd.base.BaseRecyclerAdapter;
import com.yyk.yykywd.base.BaseRecyclerHolder;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.ClientListInfo;
import com.yyk.yykywd.util.JianpanTanchuUtil;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.OnClickFlagUtil;
import com.yyk.yykywd.widght.diver.CustomDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 客户搜索
 */
public class CustomerSearchActivity extends BaseActivity {
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.ll_emptyview)
    LinearLayout llEmptyview;

    @Override
    public int getLayoutId() {
        return R.layout.activity_customer_search;
    }

    @Override
    public void initView() {
//        initEditText();
        hidetoolBar();
        JianpanTanchuUtil.getIntanse().initRuanjianpan(mActivity, etSearch);
    }

    @Override
    public void initData() {
        initAdapter();
    }

    private void initEditText() {
        //监听输入的变化
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                postDocathDisease(true);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //                postDocathDisease(true);

            }

            @Override
            public void afterTextChanged(Editable s) {
//                initAdapter();
                if (s.length() > 0)
                    postClientList(true);
            }


        });
    }

    private List<ClientListInfo.DataBean> list = new ArrayList<>();
    private BaseRecyclerAdapter<ClientListInfo.DataBean> adapter;

    private void initAdapter() {

        adapter = new BaseRecyclerAdapter<ClientListInfo.DataBean>(mActivity, list, R.layout.adapter_item_customerlist) {
            @Override
            public void convert(BaseRecyclerHolder holder, ClientListInfo.DataBean item, int position, boolean isScrolling) {
                TextView tv_state = holder.getView(R.id.tv_state);
                holder.setText(R.id.tv_hname, item.getHname());
                holder.setText(R.id.tv_name_postname_phone, item.getName() + " | " + item.getPost_name() + " | " + item.getPhone());
                String del = item.getDel();
                if (del.equals("2")) {
                    holder.getView(R.id.tv_name_postname_phone).setVisibility(View.GONE);
                    holder.setText(R.id.tv_state, "计划已删除");
                    tv_state.setTextColor(getResources().getColor(R.color.gray_b3));
                } else {
                    //当判断状态 为 已删除，未拜访:隐藏拜访信息
                    int state = item.getState();
                    if (state == 1) {
                        holder.setText(R.id.tv_state, "未拜访");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.GONE);

                    } else if (state == 2) {
                        holder.setText(R.id.tv_state, "未拜访");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.GONE);
                    } else if (state == 3) {
                        holder.setText(R.id.tv_state, "待签合同");
                    } else if (state == 4) {
                        holder.setText(R.id.tv_state, "待回款");
                    } else if (state == 5) {
                        holder.setText(R.id.tv_state, "合作成功");
                        tv_state.setTextColor(getResources().getColor(R.color.green_2a));

                    } else if (state == 6) {
                        holder.setText(R.id.tv_state, "仍需跟进");
                    } else if (state == 7) {
                        holder.setText(R.id.tv_state, "合作未达成");
                    }
                }
            }
        };
        rvList.addItemDecoration(new CustomDecoration(mActivity, CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8f_10, 0));
        rvList.setLayoutManager(new LinearLayoutManager(mActivity));
        rvList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", list.get(position).getId() + "");
                startAct(MyCustomerActivity.class, bundle);
            }
        });
    }

    /**
     * 接口31:客户列表（whm）
     *
     * @param flag
     */
    private void postClientList(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid") + "");
        map.put("name", etSearch.getText().toString().trim());

        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postClientList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Observer<ClientListInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ClientListInfo info) {
                        Logger.e("31:搜索客户列表（whm）" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                list.clear();
                            }
                            if (info.getData().size() > 0 && info.getData() != null) {
                                list.addAll(info.getData());
                            }
                            adapter.notifyDataSetChanged();
                            rvList.setVisibility(View.VISIBLE);
                            llEmptyview.setVisibility(View.GONE);
                        } else if (info.getCode() == 2) {
                            rvList.setVisibility(View.GONE);
                            llEmptyview.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.t("异常" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @OnClick({R.id.tv_search, R.id.iv_back})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_search:
                postClientList(true);
                break;
            case R.id.iv_back:
                finish();
                break;
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
